package nc.nc93;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * @author ShenTuZhiGang
 */
public class Solution {
    /**
     * lru design
     *
     * @param operators int整型二维数组 the ops
     * @param k         int整型 the k
     * @return int整型一维数组
     */
    public int[] LRU(int[][] operators, int k) {
        // write code here
        LRUCache cache = new LRUCache(k);
        List<Integer> list = new ArrayList<>();
        for (int[] cmd : operators) {
            if (cmd[0] == 1) {
                cache.put(cmd[1], cmd[2]);
            } else if (cmd[0] == 2) {
                list.add(cache.get(cmd[1]));
            }
        }
        return list.stream().mapToInt(Integer::valueOf).toArray();
    }
}

class LRUCache {
    Map<Integer, Integer> cache;
    int capacity;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        // 0.75 是数组扩容的触发条件，true 表示将结点以访问顺序排序，默认是插入顺序
        this.cache = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
                // 设置删除年长结点的触发条件为缓存满
                return size() > capacity;
            }
        };
    }

    public int get(int key) {
        // 自动调整顺序，不存在返回 -1
        return cache.getOrDefault(key, -1);
    }

    public void put(int key, int value) {
        // 自动插入，自动判满删除
        cache.put(key, value);
    }
}